package com.ihrm.system.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ihrm.common.entity.Constants;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.JwtUtil;
import com.ihrm.domain.system.*;
import com.ihrm.system.dao.PermissionDao;
import com.ihrm.system.dao.RolePermissionDao;
import com.ihrm.system.dao.UserDao;
import com.ihrm.system.dao.UserRoleDao;
import com.ihrm.system.service.UserRoleService;
import com.ihrm.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public String login(LoginDto loginDto) {
        String mobile = loginDto.getMobile();
        String password = loginDto.getPassword();
        User user = userDao.findByMobile(mobile);
        if (user == null) {
            throw new CommonException(Constants.FAIL_CODE, "用户不存在");
        }
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            throw new CommonException(Constants.FAIL_CODE, "密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", user.getCompanyId());
        map.put("companyName", user.getCompanyName());
        map.put("userId", user.getId());
        map.put("username", user.getUsername());
        String token = JwtUtil.createJWT(60 * 60 * 24 * 1000, map);
        return token;
    }

    @Override
    public ProfileResult getUserProfileByUserId(String userId) {
        User user = userDao.selectById(userId);
        if ("1".equals(userId)) {
            //获取菜单权限
            Permission menuPermission = new Permission();
            menuPermission.setType(1);
            Set<String> menus = permissionDao.findAll(menuPermission).stream().map(item -> item.getCode()).collect(Collectors.toSet());
//            获取按钮权限
            Permission ponitPermission = new Permission();
            ponitPermission.setType(2);
            Set<String> points = permissionDao.findAll(ponitPermission).stream().map(item -> item.getCode()).collect(Collectors.toSet());
            //            获取按钮权限
            Permission ApiPermission = new Permission();
            ApiPermission.setType(2);
            Set<String> apis = permissionDao.findAll(ApiPermission).stream().map(item -> item.getCode()).collect(Collectors.toSet());
            return new ProfileResult(user, menus, points, apis);
        } else {
            List<UserRole> userRoleList = userRoleDao.getRolesByUserId(userId);
            List<String> roles = userRoleList.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
            List<RolePermission> rolePermissionList = new ArrayList();
            roles.forEach(item -> {
                List<RolePermission> permissionList = rolePermissionDao.selectByRoleId(item);
                rolePermissionList.addAll(permissionList);
            });
            Set<String> permIds = new HashSet<>(); //获取拥有的权限id
            rolePermissionList.forEach(item -> {
                permIds.add(item.getPermissionId());
            });
            Set<String> menus = new HashSet<>();
            Set<String> points = new HashSet<>();
            Set<String> apis = new HashSet<>();
            permIds.forEach(item -> {
                Permission perm = permissionDao.findById(item);
                Integer type = perm.getType();
                if(type == 1) {
                    menus.add(perm.getCode());
                }else if(type == 2) {
                    points.add(perm.getCode());
                }else {
                    apis.add(perm.getCode());
                }
            });
            return new ProfileResult(user, menus, points, apis);
        }
    }

    @Override
    public Integer insert(User user) {
        user.setId(new IdWorker().nextId() + "");
        user.setCreateTime(new Date());
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        user.setEnableState(1);// 状态
        return userDao.insert(user);
    }

    @Override
    public PageResult pageFind(Integer page, Integer pagesize, Map<String, Object> map) {
        PageHelper.startPage(page, pagesize);
        Page<User> data = userDao.pageFind(map);
        return PageResult.builder().total(data.getTotal()).rows(data.getResult()).build();
    }

    @Override
    public User selectById(String id) {
        User user = userDao.selectById(id);
        List<UserRole> roles = userRoleDao.getRolesByUserId(id);
        Set<String> roleIds = new HashSet();
        roles.forEach(item -> {
            roleIds.add(item.getRoleId());
        });
        user.setRoleIds(roleIds);
        return user;
    }

    @Override
    public Integer update(User user) {
        User user1 = userDao.selectById(user.getId());
        return userDao.update(user);
    }

    @Override
    public Integer del(String id) {
        return userDao.del(id);
    }

    @Override
    public void assignRoles(String userId, List<String> roleIds) {
        userRoleService.update(userId, roleIds);
    }


}
